import io from 'socket.io-client'
import {
    AUTH_SUCCESS,
    ERROR_MSG,
    RECEIVE_USER,
    RESET_USER,
    RECEIVE_USER_LIST,
    RECEIVE_MSG_LIST,
    RECEIVE_MSG,
    MSG_READ

} from "./action-types";
import { reqLogin, reqRegister, reqUpdateUser, reqUser, reqUserList, reqChatMsgList, reqReadMsg } from "../api";
// 授权成功的同步action
const authSuccess = (user) => ({ type: AUTH_SUCCESS, data: user })
// 错误提示信息的同步action
const errorMsg = (msg) => ({ type: ERROR_MSG, data: msg })
// 接收用户的同步action
const receiveUser = (user) => ({ type: RECEIVE_USER, data: user })
// 重置用户的同步action
export const resetUser = (msg) => ({ type: RESET_USER, data: msg })
// 接收用户列表的同步action
const receiveUserList = (userList) => ({ type: RECEIVE_USER_LIST, data: userList })
// 接收消息列表的同步action
const receiveMsgList = ({ users, chatMsgs, userid }) => ({ type: RECEIVE_MSG_LIST, data: { users, chatMsgs, userid } })
// 接收一个消息的同步action
const receiveMsg = (chatMsg, userid) => ({ type: RECEIVE_MSG, data: { chatMsg, userid } })
// 读取了某个聊天消息的同步action
const msgRead = ({ count, from, to }) => ({ type: MSG_READ, data: { count, from, to } })
// 注册异步action
export const register = (user) => {
    const { username, password, password2, type } = user
    if (!username) {
        return errorMsg('用户名必须指定!')
    } else if (password !== password2) {
        return errorMsg('2次密码要一致!')
    }
    return async dispatch => {
        const response = await reqRegister({ username, password, type })
        const result = response.data
        if (result.code === 0) {
            getMsgList(dispatch, result.data._id)
            dispatch(authSuccess(result.data))
        } else {
            dispatch(errorMsg(result.msg))
        }
    }
}
// 登陆异步action
export const login = (user) => {

    const { username, password } = user
    // 做表单的前台检查, 如果不通过, 返回一个errorMsg的同步action
    if (!username) {
        return errorMsg('用户名必须指定!')
    } else if (!password) {
        return errorMsg('密码必须指定!')
    }

    return async dispatch => {
        // 发送注册的异步ajax请求
        /*const promise = reqLogin(user)
        promise.then(response => {
          const result = response.data  // {code: 0/1, data: user, msg: ''}
        })*/
        const response = await reqLogin(user)
        const result = response.data
        if (result.code === 0) {// 成功
            getMsgList(dispatch, result.data._id)
            // 分发授权成功的同步action
            dispatch(authSuccess(result.data))
        } else { // 失败
            // 分发错误提示信息的同步action
            dispatch(errorMsg(result.msg))
        }
    }
}


// 异步更新用户
export const updateUser = (user) => {
    return async dispatch => {
        const response = await reqUpdateUser(user)
        const result = response.data
        if (result.code === 0) {
            dispatch(receiveUser(result.data))
        } else {
            dispatch(resetUser(result.msg))
        }
    }
}
// 异步获取用户
export const getUser = () => {
    return async dispatch => {
        const response = await reqUser()
        const result = response.data
        if (result.code === 0) {
            getMsgList(dispatch, result.data._id)
            dispatch(receiveUser(result.data))
        } else {
            dispatch(resetUser(result.msg))
        }
    }
}
// 异步获取用户列表
export const getUserList = (type) => {
    return async dispatch => {
        const response = await reqUserList(type)
        const result = response.data
        if (result.code === 0) {
            dispatch(receiveUserList(result.data))
        }
    }
}

// 聊天功能
// 初始化客户端socketio
// 1.连接服务器
// 2.绑定用于接收服务器返回chatMsg的监听
function initIO(dispatch, userid) {
    if (!io.socket) {
        io.socket = io('ws://localhost:4000')
        io.socket.on('receiveMsg', function (chatMsg) {
            console.log(chatMsg)
            if (userid === chatMsg.from || userid === chatMsg.to) {
                dispatch(receiveMsg(chatMsg, userid))
            }
        })
    }
}
// 获取当前用户所有聊天信息列表
async function getMsgList(dispatch, userid) {
    initIO(dispatch, userid)
    const response = await reqChatMsgList()
    const result = response.data
    if (result.code === 0) {
        const { users, chatMsgs } = result.data
        // 分发同步action
        dispatch(receiveMsgList({ users, chatMsgs, userid }))
    }
}
// 发消息的异步action
export const sendMsg = ({ from, to, content }) => {
    return dispatch => {
        console.log('客户端向服务器发送消息', { from, to, content })
        io.socket.emit('sendMsg', { from, to, content })
    }
}
// 更新读取消息的异步action 
export const readMsg = (from, to) => {
    return async dispatch => {
        const response = await reqReadMsg(from)
        const result = response.data
        if (result.code === 0) {
            const count = result.data
            dispatch(msgRead({ from, to, count }))
        }
    }
}